<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 汪利东,2016-04-11 14:51
// +----------------------------------------------------------------------
namespace Admin\Controller;
class OrderController extends BaseController {

    public function index() {
        $mapstr='';
        $order_id = I('get.order_id');
        $mapstr="state_order>0";
        if (!empty($order_id)) {
            if($mapstr!=''){
                $mapstr.=' and ';
            }
            $mapstr.='a.order_id = '.$order_id;
        }
        $keywords = I('get.keywords');
        if (!empty($keywords)) {
            if($mapstr!=''){
                $mapstr.=' and ';
            }
            $mapstr.='(a.order_id like "%'.$keywords.'%" or card_id="'.$keywords.'")';
        }

        $interval_time = I('get.interval_time');
        if (!empty($interval_time)) {
            $time=explode('~',$interval_time);
            $time[0]=$time[0].' 00:00:00';
            $time[1]=$time[1].' 23:59:59';
            if($mapstr!=''){
                $mapstr.=' and ';
            }
            $mapstr.=' a.create_time >"'.$time[0].'" and a.create_time < "'.$time[1].'"';
        }

        $type = I('get.type');
        switch($type){
            case '0':
            case '1':
                if($mapstr!=''){
                    $mapstr.=' and ';
                }
                $mapstr.='a.type="'.$type.'"';
                break;
            default:break;
        }
        $online = I('get.online');
        switch($online){
            case '0':
            case '1':
                if($mapstr!=''){
                    $mapstr.=' and ';
                }
                $mapstr.='a.is_online="'.$online.'"';
                break;
            default:break;
        }

        $count = D('OrderBook')->alias('a')->join('card on a.user_id=card.user_id','left')->where($mapstr)->count();// 查询满足要求的总记录数
        $Page = new  \Admin\Common\Page($count , C('page.size'));// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $this->assign('page' , $show);// 赋值分页输出
        $data = D('OrderBook')->alias('a')->relation(true)//            ->join('left join card b on a.user_id=b.user_id')
            ->where($mapstr)
            ->join('card b on a.user_id=b.user_id','left')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->order('a.create_time desc')
            ->select();
        foreach ($data as $key => $val) {
            $data[ $key ]['address'] = json_decode($val['address'] , TRUE);
            if(!empty($val["order_broken"])){
                foreach ($val["order_broken"] as $k => $v){
                    $b = M("book")->where(["book_id"=>$v["book_id"]])->find();
                    $data[ $key ]["order_broken"][$k] = array_merge($data[ $key ]["order_broken"][$k],$b);
                }
            }
            // 不知道为什么动态关联那里没有想要的数据
            $data[$key]['product'] = M('order_has_product')->where(['order_id' => $val['order_id']])
                    ->join('product on product.product_id = order_has_product.product_id')->select();
        }
        if(I("get.execl")==1){

            $data = D('OrderBook')->alias('a')
                ->relation(TRUE)
                ->join('left join card b on a.user_id=b.user_id')
                ->where($mapstr)
                ->field('b.card_id,a.*')->order('a.create_time desc')
                ->order('a.create_time desc')
                ->select();
            foreach ($data as $key => $val) {
                unset($data[$key]['user']);
                unset($data[$key]['card']);
                unset($data[$key]['pay']);
//                unset($data[$key]['order_broken']);
                if(!empty($val["order_broken"])){
                    foreach ($val["order_broken"] as $k => $v){
                        $b = M("book")->where(["book_id"=>$v["book_id"]])->find();
                        $data[ $key ]["order_broken"][$k] = array_merge($data[ $key ]["order_broken"][$k],$b);
                    }
                }
            }
//            dump($data);exit;

            $this->export($data);
        }else{
            $this->data = $data;
            $this->display();
        }
    }

    function export($data) {
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能import导入
        import("Common.PHPExcel.PHPExcel" , '' , '.php');
        import("Common.PHPExcel.PHPExcel.Writer.Excel2007" , '' , '.php');
        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        //或者$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel); 非2007格式
        //    设置当前的sheet
        $objPHPExcel->setActiveSheetIndex(0);
        //    设置sheet的name
        $objPHPExcel->getActiveSheet()->setTitle('Data');
        //订单字段
        $orderList = ['card_id','order_id','user_id','money','price_freight','type','address','state_order','is_print','pay_id','create_time','is_freightfree','discount_buy','is_refund','is_online','refund_id','order_remark'];
        //订单详情字段
        $bookList = ['order_has_book_id','order_id','quantity','type','spbs','sm','zyz','dj','bb','tm','is_del','num_backed','num_broken','state_order'];

        $row = 1;
        $letter=1;
        foreach ($orderList as $key=>$val){
            $objPHPExcel->getActiveSheet()->setCellValue(convert_10to26($letter++).$row, $val);
        }
        foreach ($bookList as $key=>$val){
            $objPHPExcel->getActiveSheet()->setCellValue(convert_10to26($letter++).$row, $val);
        }

        $row = 2;
        $bookLetter = count($orderList)+1;
        foreach ($data as $key=>$val){
            $letter=1;
            foreach ($orderList as $k=>$v){
                $objPHPExcel->getActiveSheet()->setCellValue(convert_10to26($letter++).$row, $val[$v]);
            }
            if(!empty($val['order_has_book'])){
                foreach ($val['order_has_book'] as $bk=>$bv){
                    $letter = $bookLetter;
                    foreach ($bookList as $k=>$v){
                        $objPHPExcel->getActiveSheet()->setCellValue(convert_10to26($letter++).$row, $bv[$v]);
                    }
                    $row++;
                }
            }else{
                $row++;
            }
        }
        //    保存excel—2007格式
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $filename = 'export_' . date('YmdHis') . ".xlsx";
        $filepath = "uploads/excel/" . $filename;
        $objWriter->save($filepath);
        ouput_Browser($filepath);

        exit;


//        $mapstr="state_order>0";
//        $data = D('OrderBook')->alias('a')
//            ->join('left join card b on a.user_id=b.user_id')
//            ->where($mapstr)
//            ->field('b.card_id,a.*')->order('a.create_time desc')
//            ->limit(100)
//            ->select();
//
//
//        $file = excel_export($data);
//        ouput_Browser($file);
    }

    function add() {
        $delivery_man = M("Delivery_man");
        $dman = $delivery_man->field("man_id,name,phone")->select();
        $this->assign("dman" , $dman);
        $this->display("edit");
    }

    function edit() {
        $delivery_man = M("Delivery_man");
        $dman = $delivery_man->field("man_id,name,phone")->select();
        $order_id = I("get.order_id");
        $Odelivery = M("Order_delivery");
        $d = $Odelivery->where("order_id={$order_id}")->find();
        $content = json_decode($d['content']);
        $d['content'] = array ();
        $d['content']['name'] = $content->name;
        $d['content']['order_num'] = $content->order_num;
        $this->assign("d" , $d);
        $this->assign("dman" , $dman);
        $this->display();
    }

    function doEdit() {
        $type = I("post.type");
        $order_id = I("get.order_id");
        $Odelivery = M("Order_delivery");
        $count = $Odelivery->where("order_id={$order_id}")->count();
        $data['type'] = $type;
        $data['state_order'] = 2;
        switch ($type) {
            case 1:
                $data['man_id'] = I("post.man_id");
                $dc['name'] = I("post.name");
                $dc['phone'] = I("post.phone");
                break;
            case 2:
                $dc['name'] = I("post.delivery_name");
                $dc['order_num'] = I("post.order_num");
                break;
            default:
                break;
        }
        $data['content'] = json_encode($dc , JSON_UNESCAPED_UNICODE);
        if ($count > 0) {
            //修改发货信息
            $Odelivery->startTrans();
            $d = $Odelivery->where("order_id={$order_id}")->data($data)->save();
            if ($d) {
                $Odelivery->commit();
                $this->success("修改成功" , U("index"));
            } else {
                $Odelivery->rollback();
                $this->error("修改失败");
            }
        } else {
            $data['order_id'] = $order_id;
            //添加发货信息
            $Odelivery->startTrans();
            $delivery_id = $Odelivery->data($data)->add();
            //更改订单状态
            $Order = M("Order_book");
            $r = $Order->where("order_id={$order_id} && state_order=1")->data("state_order=2")->save();
            if ($delivery_id && $r) {
                // todo 把未分配的订单进行分配
                $user_id = $Order->where(['order_id' => $order_id])->getField('user_id');
                M('order_has_product')->where(['user_id' => $user_id, '_string' => 'order_id is null'])->setField('order_id', $order_id);
                $Odelivery->commit();
                $this->success("发货成功" , U("index"));
            } else {
                $Odelivery->rollback();
                $this->success("发货失败");
            }
        }
    }
    //获取订单数据-ajax修改订单
    function getOrder(){
        $order_id=I('post.order_id');
        $mapstr='order_id="'.$order_id.'"';
        $d = D('OrderBook')->alias('a')->relation(TRUE)//            ->join('left join card b on a.user_id=b.user_id')
        ->where($mapstr)->join('card b on a.user_id=b.user_id','left')
            ->field('a.*,b.card_id')->order('a.create_time desc')
            ->find();
        $j=[
            'status'=>'success',
            'data'=>$d
        ];
        echo json_encode($j,JSON_UNESCAPED_UNICODE);
    }
    //修改订单-ajax
    function saveOrder(){
        $order_id=I('post.order_id');
        $booklist=I('post.booklist');
        //检查
        $OrderBook=M('Order_has_book');
        $c=$OrderBook->where(['order_id'=>$order_id])->count();
        $c1=$OrderBook->where(['order_id'=>$order_id,'type'=>'1','is_backed'=>'0','num_backed'=>'0','num_broken'=>'0'])->count();
        if($c!=$c1){
            $j=[
                'status'=>'error',
                'data'=>'无法修改订单,已有图书归还或回收'
            ];
            echoJson($j);
            exit();
        }
        $OrderBook->startTrans();
        $OrderBook->where(['order_id'=>$order_id,'type'=>'1'])->delete();
        $booklist_t=[];
        //对图书数据整合,如书本一样的数量合并
        foreach($booklist as $k=>$v){
            if(array_key_exists($k,$booklist_t)){
                //存在即数量增加
                $booklist_t[$v['book_id']]['quantity']+=$v['quantity'];
            }else{
                //不存在即创建
                $booklist_t[$v['book_id']]['quantity']=$v['quantity'];
                $booklist_t[$v['book_id']]['book_id']=$v['book_id'];
            }
            unset($booklist[$k]);
        }
        foreach($booklist_t as $k=>$v){
            if($v['quantity']=='0'){
                continue;
            }
            //修改订单
            $r=$OrderBook->data(['order_id'=>$order_id,'type'=>'1','book_id'=>$v['book_id'],'quantity'=>$v['quantity']])->add();
            if(!$r){
                $OrderBook->rollback();
                $j=[
                    'status'=>'error',
                    'data'=>'更新失败'
                ];
                echoJson($j);
                exit();
            }
        }
        $OrderBook->commit();
        $j=[
            'status'=>'success',
            'data'=>'修改成功'
        ];
        echoJson($j);
    }
}